package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
public class OrderTask {
    @Resource
    private OrdersMapper ordersMapper;

    //定时处理订单状态(订单超时15分钟自动取消订单)
    @Scheduled(cron = "0 * * * * *")
    public void processTimeoutOrder() {
        log.info("定时处理超时订单：{}", LocalDateTime.now());
        //select * from orders where status = ? and order_time < 当前时间 - 15min
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        List<Orders> ordersList = ordersMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT, time);
        if (ordersList != null && ordersList.size() > 0) {
            for (Orders orders : ordersList) {
                Orders ordersDB = new Orders();
                ordersDB.setId(orders.getId());
                ordersDB.setStatus(Orders.CANCELLED);
                ordersDB.setCancelTime(LocalDateTime.now());
                ordersDB.setCancelReason("订单超时，自动取消");
                ordersMapper.update(ordersDB);
            }
        }
    }

    //每天凌晨一点触发一次(处理派送中的订单)
    @Scheduled(cron = "0 0 4 * * *")
    public void processDeliveryOrder() {
        log.info("定时处理派送中的订单：{}", LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);

        List<Orders> ordersList =ordersMapper.getByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS, time);// 派送中
        if (ordersList != null && ordersList.size() > 0) {
            for (Orders orders : ordersList) {
                Orders ordersDB = new Orders();
                ordersDB.setId(orders.getId());
                ordersDB.setStatus(Orders.COMPLETED);
                ordersMapper.update(ordersDB);
            }
        }

    }
}
